//
//  HomeView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2024/12/24.
//

import SwiftUI
struct HomeView:View {
    @EnvironmentObject var pathManager: PathManager
    @EnvironmentObject var userManager: UserManager
    @StateObject var viewModel = HomeViewModel()
    @State private var isBubbleBackups2 = false
    @State private var isBubbleTime2 = false
    // 定时器
    @State private var timerBubbleBackups: Timer?
    @State private var timerBubbleTime: Timer?
    @State var showComment = false
    
    @State private var selectId = ""
    @State var curDate = Date()
    var body: some View {
        ZStack {
            // 背景层
            BackgroundView(isMain: true)
            VStack(spacing:0) {
                HStack(spacing:0) {//取消之间的间距
                    timeView
                    classsifyView
                        .frame(maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/)
                        .padding(.top, 6)//由于timeView自定义字体顶部间距过大
                    Menu {
                        Button("备份模式") {
                            showBackupsPopup()
                        }
                        Button("时间试图切换") {
                            showDateModePopup()
                        }
                        Button("选择时间") {
                            showTimeModePopup()
                        }
                    } label: {
                        Image(.homeIconMore2)
                            .resizable()
                            .frame(width: 25, height: 25)
                            .padding(.trailing, 10)
                            .padding(.top, 8)//由于timeView自定义字体顶部间距过大
                    }
                    
                }.frame(maxWidth: .infinity)
                //备份切换
                HStack{
                    HStack(spacing:4) {
                        Image(BackupsManager.shared.getBackupsIcon())
                            .resizable()
                            .frame(width: 12,height: 12)
                        Text(BackupsManager.shared.getBackupsName())
                            .font(.system(size: 12))
                            .foregroundStyle(.bgNormalText)
                    }.padding(.top, 4)
                        .tooltip(isPresented: $isBubbleBackups2) {
                            Text("点击可切存储模式，本地存储、官方存储")
                                .font(.system(size: 14))
                        }
                        .contentShape(Rectangle())
                        .onTapGesture {
                            showBackupsPopup()
                        }
                    Spacer()
                }.padding(.leading, 22)
                pageView.padding(.top, 10)
            }
        }
        .background(.bg)
        .sheet(isPresented: $showComment) {
            //为啥评论要在这个界面做弹窗，而不是各自的view里面去弹窗
            //因为itemView随时会更新，会导致弹窗自动关闭问题
            if let diary = viewModel.commentDiaryBean {
                DiaryCommentDialogView(bean: diary, aiRoleId: viewModel.commentAiRoleId ?? "").presentationDetents([.fraction(0.9), .large])
            }
        }
        .onReceive(viewModel.$showComment) { value in
            //评论展开
            showComment = value
        }
        .onChange(of: AppStorageManager.shared.toggleAiDiary) { value in
            //ai 日记开关
            viewModel.tableItem.removeAll()
            viewModel.getTab()
        }
        .onChange(of: userManager.isLoginSuc) { value in
            showLog("首页刷新登陆")
            selectId = userManager.getUserId()
            viewModel.getTab(true)
        }
        .onChange(of: BackupsManager.shared.backupsType) { value in
            showLog("首页备份切换")
            selectId = userManager.getUserId()
            viewModel.getTab(true)
        }.onChange(of: selectId) { newValue in
            viewModel.setBackground(aiRoleId: newValue)
        }.onAppear{
            if !viewModel.isInit {
                if isExamine() {
                    //审核版本，强制改成年试图
                    AppStorageManager.shared.dateMode = IDateModeType.YEAR
                }
                viewModel.isInit = true
                selectId = userManager.getUserId()
                viewModel.getTab()
                showBubbleTime()
            } else {
                //首次在selectId变更会触发，这边就无需在调用，这边只是用于切换到别的页面回调回来
                viewModel.setBackground(aiRoleId: selectId)
            }
        }
    }
    //显示气泡
    private func showBubbleTime() {
        if AppStorageManager.shared.isBubbleTime {
            isBubbleTime2 = true
            startCountdown(10) {
                AppStorageManager.shared.isBubbleTime = false
                isBubbleTime2 = false
                showBubbleBackups()
            }
        } else {
            showBubbleBackups()
        }
    }
    
    private func showBubbleBackups() {
        if AppStorageManager.shared.isBubbleBackups {
            isBubbleBackups2 = true
            startCountdown(10) {
                AppStorageManager.shared.isBubbleBackups = false
                isBubbleBackups2 = false
            }
        }
    }
}

extension HomeView {
    //时间试图
    var timeView : some View {
        ZStack(alignment:.leading) {
            Text("")
                .padding(.horizontal,30)
                .tooltip(isPresented: $isBubbleTime2) {
                    Text("点击切换时间，即刻查看当日日记\n长按时间区域，切换全年日记记录、整月日记记录")
                        .font(.system(size: 14))
                }
            HStack(spacing : 0) {
                switch AppStorageManager.shared.dateMode{
                case .DAY:
                    Text(TimeUtils.getDate(date: curDate, format: "M"))
                        .bold()
                        .font(.custom(IFontType.number.rawValue, size: 30))
                        .fontWeight(.bold)
                        .foregroundColor(.bgNormalText)
                    Text("月")
                        .font(.system(size: 12))
                        .foregroundColor(.bgNormalText4)
                        .padding(.horizontal,2)
                        .frame(height: 28,alignment: .bottom)
                    Text(TimeUtils.getDate(date: curDate, format: "d"))
                        .bold()
                        .font(.custom(IFontType.number.rawValue, size: 30))
                        .fontWeight(.bold)
                        .foregroundColor(.bgNormalText)
                case .MONTH:
                    Text(TimeUtils.getDate(date: curDate, format: "yy"))
                        .bold()
                        .font(.custom(IFontType.number.rawValue, size: 30))
                        .fontWeight(.bold)
                        .foregroundColor(.bgNormalText)
                    Text("年")
                        .font(.system(size: 12))
                        .foregroundColor(.bgNormalText4)
                        .padding(.horizontal,2)
                        .frame(height: 28,alignment: .bottom)
                    Text(TimeUtils.getDate(date: curDate, format: "M"))
                        .bold()
                        .font(.custom(IFontType.number.rawValue, size: 30))
                        .fontWeight(.bold)
                        .foregroundColor(.bgNormalText)
                case .YEAR:
                    Text(TimeUtils.getDate(date: curDate, format: "yy"))
                        .bold()
                        .font(.custom(IFontType.number.rawValue, size: 30))
                        .fontWeight(.bold)
                        .foregroundColor(.bgNormalText)
                    Text("年")
                        .font(.system(size: 12))
                        .foregroundColor(.bgNormalText4)
                        .padding(.horizontal,2)
                        .frame(height: 28,alignment: .bottom)
                }
            }
        }
        .padding(.leading, 20)
        .contentShape(Rectangle())
        .onTapGesture {
            showTimeModePopup()
        }
        .onLongPressGesture {
            showDateModePopup()
        }
    }
    
    //功能弹窗
    func showFunctionPopup() {
        SwiftEntryKitWrapper.showBottomPopup{ dismiss in
            HomeFunctionDialogView() {
                dismiss()
            }
        }
    }
    
    //日期模式
    func showDateModePopup() {
        AppStorageManager.shared.isBubbleTime = false
        isBubbleTime2 = false
        SwiftEntryKitWrapper.showBottomPopup{ dismiss in
            DateModeDialogView() {
                dismiss()
            }
        }
    }
    
    //根据日期，选择时间弹窗
    func showTimeModePopup() {
        AppStorageManager.shared.isBubbleTime = false
        isBubbleTime2 = false
        switch AppStorageManager.shared.dateMode {
        case IDateModeType.YEAR:
            SwiftEntryKitWrapper.showBottomPopup { dissmis in
                PickDateView(title: "    选择日期", selectedDate: $curDate,yearView: true,monthView: false, dayView: false, hourView : false, minuteView: false) {
                    dissmis()
                }
            }
        case IDateModeType.MONTH:
            SwiftEntryKitWrapper.showBottomPopup { dissmis in
                PickDateView(title: "    选择日期", selectedDate: $curDate,yearView: true,monthView: true, dayView: false, hourView : false, minuteView: false) {
                    dissmis()
                }
            }
        case IDateModeType.DAY:
            SwiftEntryKitWrapper.showBottomPopup { dissmis in
                PickDateView(title: "    选择日期", selectedDate: $curDate,yearView: true,monthView: true, dayView: true, hourView : false, minuteView: false) {
                    dissmis()
                }
            }
        }
        
    }
    //备份模式
    func showBackupsPopup(){
        AppStorageManager.shared.isBubbleBackups = false
        isBubbleBackups2 = false
        SwiftEntryKitWrapper.showBottomPopup { dismiss in
            BackupsSwitchDialogView() {
                dismiss()
            }
        }
    }
}

extension HomeView {
    //标签分类
    var classsifyView: some View {
        ScrollView(.horizontal,showsIndicators: false) {
            VStack(alignment: .leading, spacing: 0){
                //滚动试图（通过HStack监听selectIndex 变化，实现滚动标签）
                ScrollViewReader { value in
                    //横向布局
                    HStack(spacing:0) {
                        ForEach(viewModel.tableItem, id: \.uuid) { item in
                            HStack(spacing: 0) { //间距为0
                                //文本
                                Text(item.name)
                                    .font(.system(size: item.id == selectId ? 20 : 15))
                                    .fontWeight(item.id == selectId ? .semibold : .regular)
                                    .foregroundColor(.bgNormalText.opacity(item.id == selectId ? 1 : 0.3))
                                    .padding(0)
                                if item.red {
                                    //红点
                                    VStack{
                                        Circle().fill(Color.red)
                                            .frame(width: 5, height: 5)
                                        Spacer()
                                    }.frame(height: 20)
                                }
                            }.padding(.horizontal, 10)
                                .padding(.top, 5)                            .onTapGesture {
                                    withAnimation{
                                        self.selectId = item.id
                                    }
                                    //                                     withAnimation(Animation.linear(duration: 2)) { //加个动画，标题滚动到中间才不会生硬
                                    //                                         value.scrollTo(selectIndex,anchor: .center)
                                    //                                     }
                                }
                            
                        }
                    }.padding(.leading,10).padding(.trailing,10) //内部滚动间距
                    //监听试图，让他滚动的时候居中，不支持16
                        .onChange(of: selectId) { newValue in
                            let selectIndex = viewModel.tableItem.firstIndex(where: { $0.id == newValue })
                            withAnimation(Animation.linear(duration: 2)) { //加个动画，标题滚动到中间才不会生硬
                                value.scrollTo(selectIndex,anchor: .center)
                            }
                            if viewModel.tableItem.count > (selectIndex ?? 0) {
                                viewModel.tableItem[selectIndex ?? 0].red = false //取消红点
                            }
                        }
                }
                //指示器，目前的指示器只能固定大小，应该是需要跟文本一样的宽度才行
                //                     HStack{
                //                         Capsule().fill(Color.red).frame(width: 20,height: 2)
                //                     }.frame(width: 50)
                //                         .offset(x: CGFloat(selectIndex * 50))
                //                         .animation(Animation.linear(duration: 0.2),value: selectIndex)
            }
        }.padding(.trailing,10)
        
    }
}

extension HomeView{
    private var pageView : some View {
        ZStack {
            TabView(selection: $selectId) { //使用selection 就会跟$selectIndex绑定
                ForEach(viewModel.tableItem, id: \.uuid) { item in
                    if item.id == userManager.getUserId() {
                        HomeOwnView(item: item, curDate: self.$curDate).id(item.id).tag(item.id)
                    } else {
                        //从外部传递，避免viewmodel复用
                        HomeAiView(item: item).id(item.id).tag(item.id)
                    }
                }
                
            }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))//使用PageTabViewStyle风格
        }
    }
}

//#Preview {
//    HomeView()
//}

//定义预览提供者
struct Home_Previews: PreviewProvider {
    static var previews: some View {
        //使用预览共享配置
        configurePreviewEnvironment(for: HomeView())
    }
}
